
<template>
  <section class="add">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="form.studentName"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="form.sex" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学院">
        <el-select v-model="form.college.name" placeholder="请选择学院">
          <el-option :label="item" :value="item" v-for="item in form.college" :key="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属专业">
        <el-input v-model="form.major"></el-input>
      </el-form-item>
      <el-form-item label="年级">
        <el-input v-model="form.grade"></el-input>
      </el-form-item>
      <el-form-item label="班级">
        <el-input v-model="form.clazz"></el-input>
      </el-form-item>
      <el-form-item label="电话号码">
        <el-input v-model="form.tel"></el-input>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="form.cardId"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit()" icon="el-icon-a-07">立即创建</el-button>
        <el-button type="danger" icon="el-icon-a-022" @click="cancel()">取消</el-button>
      </el-form-item>
      <el-form-item style="width: 800px">
        <el-upload
          class="upload-demo"
          action="/api/student/file"
          :on-success="handleSuccess"
          :before-remove="beforeRemove"
          style="width: 140px;float: left;margin-right: 10px"
        >
          <el-button type="primary">大数据excel上传</el-button>
        </el-upload>
        <el-upload
          class="upload-demo"
          action="#"
          multiple
          accept=".xls,.xlsx"
          style="width: 140px;float: left"
          :before-upload="excelAnalysis"
        >
          <el-button type="primary" icon="el-icon-a-07">从excel上传</el-button>
        </el-upload>

        <el-button  style="width: 160px" plain type="primary" icon="el-icon-a-07" @click="dialogVisible = true"> excel上传格式</el-button>
        <el-dialog
          title="批量添加学生格式"
          :visible.sync="dialogVisible"
          width="40%"
          :before-close="handleClose">
          <span>excel表的表头格式:<br>studentName, grade, major, clazz, institute, tel, email, pwd, cardId, sex, role <br>一列一个字段 ,可点击查看实例图片</span>
          <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="url"
              :preview-src-list="srcList">
            </el-image>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
          </span>
        </el-dialog>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
/* eslint-disable */
//用于解析excel文件
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      form: { //表单数据初始化
        studentName: null,
        grade: null,
        major: null,
        clazz: null,
        institute: null,
        tel: null,
        email: null,
        pwd: null,
        cardId: null,
        sex: null,
        role: 2,
        college:[]
      },
      collegeName:'',
      dialogVisible: false,//弹窗
      url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',//图片地址
      srcList: [
        require('../../assets/img/excel-tjxs.png'),//excel提示图片地址
      ],
      rules:{
        studentName:[
          {required:true,  trigger: 'blur',message:'姓名不能为空' },
        ],
        sex:[
          {required:true,message:'性别不能为空', trigger: ['blur','change'] },
        ],
        institute:[
          {required:true, message:'学院不能为空', trigger: ['blur','change']},
        ],
        major:[
          {required:true,message:'专业不能为空',trigger:'blur'}
        ],
        grade:[
          {required:true,message:'年级不能为空',trigger:'blur'}
        ],
        clazz:[
          {required:true,message:'班级不能为空',trigger:'blur'}
        ],
        tel:[
          {required:true,message:'电话不能为空',trigger:'blur'}
        ],
        cardId:[
          {required:true,message:'身份证号不能为空',trigger:'blur'}
        ],
        email:[
          {required:true,message:'邮箱不能为空',trigger:'blur'}
        ],
        pwd:[
          {required:true,message:'密码不能为空',trigger:'blur'}
        ],
      }
    };
  },
  methods: {
    //解析提交的excel表格
    async excelAnalysis(file) {
      //定义列名（添加学生所需要的数据）
      const list = ["studentName", "grade", "major", "clazz", "institute", "tel", "email", "pwd", "cardId", "sex", "role"];
      //将上传的文件转换为二进制（ArrayBuffer），因为XLSX只能解析二进制文件
      //添加异步“await”，等待文件解析，否则会直接执行后面的代码，然后报错
      const f = await file.arrayBuffer();
      //调用xlsx的read方法，将二进制文件解析成workbook对象
      const workbook = XLSX.read(f);
      //首先通过workbook.SheetNames[0]获取到workbook中第一个工作表的名称，然后再通过workbook.Sheets获取到该工作表对应的对象
      const first_sheet = workbook.Sheets[workbook.SheetNames[0]];
      //将对象转换为json格式，默认第一行为每列的属性名
      const data = XLSX.utils.sheet_to_json(first_sheet);
      //获取列名
      const headerdata = XLSX.utils.sheet_to_json(first_sheet, {header: 1})[0];
      if (!headerdata.every(element => list.includes(element))) {
        this.$message.error('excel表格式错误');
        return
      }
      const jsondata = JSON.stringify(data);
      this.$axios({
        url: '/api/studentList',
        method: 'post',
        headers: {
          'Content-Type': 'application/json'
        },
        data: jsondata
      }).then(res => {
        if (res.data.code == 200) {
          this.$message({
            message: '数据添加成功',
            type: 'success'
          })
          this.$router.push({path: '/studentManage'})
        }
      })
    },
    onSubmit(formName) { //数据提交
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios({
            url: '/api/student',
            method: 'post',
            data: {
              ...this.form
            }
          }).then(res => {
            if (res.data.code == 200) {
              this.$message({
                message: '数据添加成功',
                type: 'success'
              })
              this.$router.push({path: '/studentManage'})
            }
          })
        } else {
          console.log('数据不合格');
          return false;
        }
      });
    },
    getCollege(){
      this.$axios(`/api/college/selectAllCollege/1/999`).then(res => {
        this.collegeName = res.data.data.records
      }).catch(error => {});
    },
    cancel() { //取消按钮
      this.form = {}
    },
    // 关闭对话框
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    // 是否删除文件
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    //是否上传成功
    handleSuccess(res) {
      console.log(res)
      if (res.code === 200) {
        this.$message({
          message: '上传成功,成功数据为：'+res.data+"条",
          type: 'success'
        });
      } else {
        this.$message.error('上传失败,成功数据为：'+res.data+"条");
      }
    },
  },
  mounted() {
    this.getCollege()
  },

};
</script>
<style lang="less" scoped>
.add {
  padding: 0 40px;
  width: 400px;
}

</style>

